/**
 * Created by shidaiapp on 2017/9/29.
 */
import actionUrls from "../../../../api/ApiUrls";
import {createDownloadForm} from "../../../js/downloadUtils"
import {isEmpty} from "../../../js/commonUtils";

function changeModelLoading(self, tiyData) {
  tiyData.tStatus.modalClear.isLoading = false;
  self.$nextTick(function () {
    tiyData.tStatus.modalClear.isLoading = true;
  });
}
/**
 * 初始化
 * @param self
 * @param tiyData
 */
export const init = (self, tiyData) => {
  //resetForm(self, tiyData);
  tiyData.tPage.total = 1;
  tiyData.tPage.startIndex = 0;
  tiyData.tPage.stepNumber = 40;
  tiyData.tPage.currentPage = 1;
  tiyData.tParams.firstName = '';
  tiyData.tParams.contactEmail = '';
  tiyData.tParams.startEndDate = [];
  tiyData.tParams.orderBy = '';
  tiyData.tParams.selectedUsers=[];
  tiyData.tData.loginTypeDict = self.$store.getters.dictionaries.loginTypeDict;
  tiyData.tData.orderItemDict = self.orderItemDict;

  getTagList(self, tiyData);
 };

function getTagList(self, tiyData){
  self.$ySpliceAll(tiyData.tData.tabList);
  let param = {
    "type": 2
  };

  self.$apiOther.queryManageTabs(param).then(function (response) {
    if(response.success){
      response.result.forEach(function(item){
        tiyData.tData.tabList.push(item);
      })
    }else{
      self.$Message.error(response.errorMessage);
    }
  });
}

/**
 * 清理操作记录
 * @param self
 * @param tiyData
 */
export const webClearOperationRecord = function (self, tiyData) {
  tiyData.tStatus.modalClear.isLoading = true;
  self.$apiRole.clearOperationRecord()
    .then(function (response) {
      tiyData.tStatus.modalClear.isShow = false;
      changeModelLoading(self, tiyData);
      if (response.success) {
        self.$Message.success('清除成功!');
      } else {
        tiyData.tStatus.modalClear.isLoading = false;
        self.$Message.error(response.errorMessage);
      }
    });
};


/**
 * 从服务器请求列表
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webList = (self, tiyData) => {
  if(tiyData.tParams.tabId==undefined){
    tiyData.tParams.tabId='';
  }
  self.$Spin.show();
  tiyData.tParams.selectedUsers.splice(0);
  self.isCheckedAll=false;
  self.$ySpliceAll(tiyData.tData.userList);
  self.$apiUser.getUserList({
    "pageSize": tiyData.tPage.stepNumber,
    "pageNum": tiyData.tPage.currentPage,
    "firstName": tiyData.tParams.firstName,
    "contactEmail": tiyData.tParams.contactEmail,
    "startDate": isEmpty(tiyData.tParams.startEndDate[0])?"":self.$tiyQueryTime(new Date(tiyData.tParams.startEndDate[0]).getTime()),
    "endDate":  isEmpty(tiyData.tParams.startEndDate[1])?"":self.$tiyQueryTime(new Date(tiyData.tParams.startEndDate[1]).getTime()),
    "orderBy": tiyData.tParams.orderBy,
    "tabId": tiyData.tParams.tabId,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      let userPage = response.result;
      tiyData.tPage.total = userPage.total;
      tiyData.tPage.stepNumber = userPage.pageSize;
      userPage.list.forEach(
        function (item) {
          tiyData.tData.userList.push(item);
        }
      );
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};
/**
 * 从服务器请求订单列表
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webOrderList = (self, tiyData) => {
  self.$Spin.show();
  self.$apiUser.getUserOrders({
    "userId": tiyData.tParams.showOrder.userId,
    "pageNum": tiyData.tParams.showOrder.pageNum,
    "pageSize": tiyData.tParams.showOrder.pageSize
  }).then(function (response) {
    self.$ySpliceAll(tiyData.tData.orderList);
    self.$Spin.hide();
    if (response.success) {
      let orderPage = response.result;
      tiyData.tParams.showOrder.total = orderPage.total;
      orderPage.list.forEach(
        function (item) {
          tiyData.tData.orderList.push(item);
        }
      );
      tiyData.tStatus.modalOrder.isShow = true;
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};
/**
 * 从服务器请求购物车列表
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webCartList = (self, tiyData) => {
  self.$Spin.show();
  tiyData.tData.cartPriceCount = 0;
  tiyData.tData.cartWeightCount = 0;
  self.$apiUser.getShoppingCart({
    pageSize: tiyData.searchInfoPage.stepNumber,
    pageNum: tiyData.searchInfoPage.currentPage,
    userId: tiyData.tParams.showCart.userId,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.tData.cartList.splice(0,tiyData.tData.cartList.length);
      tiyData.searchInfoPage.total = response.result.data.total;
      tiyData.searchInfoPage.stepNumber = response.result.data.pageSize;
      let cartList = response.result.data.list;
      cartList.forEach(
        function (item) {
          tiyData.tData.cartList.push(item);
        }
      );
      tiyData.tData.cartWeightCount = response.result.sumWeight + 'g';
      tiyData.tData.cartPriceCount = '$' + response.result.sumPrice.toFixed(2);
      tiyData.tStatus.modalCart.isShow = true;
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};
/**
 * 从服务器请求用户地址列表
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webAddressList = (self, tiyData) => {
  self.$Spin.show();
  self.$apiUser.getUserAddress({
    "userId": tiyData.tParams.showAddress.userId,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.tData.addressList.length = 0;
      let userAddressesList = response.result;
      userAddressesList.forEach(
        function (item) {
          tiyData.tData.addressList.push(item);
        }
      );
      tiyData.tStatus.modalAddress.isShow = true;
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};
/**
 * 从服务器请求操作记录列表
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webRecordList = (self, tiyData) => {
  self.$Spin.show();
  self.$apiUser.getLoginRecords({
    "userId": tiyData.tParams.showRecord.userId,
    "pageNum": tiyData.tParams.showRecord.pageNum,
    "pageSize": tiyData.tParams.showRecord.pageSize,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.tData.recordList.length = 0;
      let recordPage = response.result;
      tiyData.tPage.pageSize = recordPage.pageSize;
      tiyData.tParams.showRecord.total = recordPage.total
      recordPage.list.forEach(
        function (item) {
          tiyData.tData.recordList.push(item);
        }
      );
      tiyData.tStatus.modalRecord.isShow = true;
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};
/**
 * 导出excel
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const exportUser = (self, tiyData) => {
  self.$Spin.show();
  self.$apiUser.exportUser({
    "firstName": tiyData.tParams.firstName,
    "contactEmail": tiyData.tParams.contactEmail,
    "startDate":  isEmpty(tiyData.tParams.startEndDate[0])?"":self.$tiyQueryTime(new Date(tiyData.tParams.startEndDate[0]).getTime()),
    "endDate":  isEmpty(tiyData.tParams.startEndDate[1])?"":self.$tiyQueryTime(new Date(tiyData.tParams.startEndDate[1]).getTime())
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      let downloadForm = createDownloadForm(response.result, actionUrls.URL_DOWNLOAD_EXCEL);
      downloadForm.submit();
    }else{
      self.$Message.error(response.errorMessage);
    }
  });
};

export const userInfo = (self, tiyData,userId) => {
  tiyData.tData.note.userId=userId;
  self.$Spin.show();
  self.$apiUser.getUserInfo({
    "userId": userId,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      let record = response.result;
      tiyData.tParams.showUserInfo=[];
        tiyData.tParams.showUserInfo.firstName=record.user.firstname;
        tiyData.tParams.showUserInfo.lastName=record.user.lastname;
        var way = '';
      self.$store.getters.dictionaries.loginTypeDict.forEach(function (item) {
        if (item.value == record.user.thirdParty) {
          way = item.name;
          return;
        }
      });
        tiyData.tParams.showUserInfo.thirdParty=way;

        var stateStr = '';
      self.$store.getters.dictionaries.userStateDict.forEach(function(item){
        if(item.value==record.user.state){
          stateStr = item.name;
          return;
        }
      });
      tiyData.tParams.showUserInfo.state=record.user.stateStr;
        tiyData.tParams.showUserInfo.country=record.user.countryName;
        tiyData.tParams.showUserInfo.phone=record.user.phone;
        tiyData.tParams.showUserInfo.email=record.user.email;
        tiyData.tParams.showUserInfo.contactEmail=record.user.contactEmail;
        tiyData.tParams.showUserInfo.isPushMessage=record.user.isPushMessage==1?true:false;
        tiyData.tParams.showUserInfo.isAdEmail=record.user.isAdEmail==1?true:false;
        tiyData.tParams.showUserInfo.userId=record.user.id;
        tiyData.tParams.showUserInfo.tabList=record.tabList;

        if(record.user.tabList){
          tiyData.tParams.showUserInfo.tabList = [];
          record.user.tabList.forEach(function(item){
            tiyData.tParams.showUserInfo.tabList.push(item.id);
          });
        }

        if(record.extendInfo!=null){
          tiyData.tParams.showUserInfo.facebook=record.extendInfo.facebook;
            tiyData.tParams.showUserInfo.whatsapp=record.extendInfo.whatsapp;
            tiyData.tParams.showUserInfo.twitter=record.extendInfo.twitter;
            tiyData.tParams.showUserInfo.instagram=record.extendInfo.instagram;
            tiyData.tParams.showUserInfo.source=record.extendInfo.source;
            tiyData.tParams.showUserInfo.inviteCode=record.extendInfo.inviteCode;
            tiyData.tParams.showUserInfo.useContent=record.extendInfo.useContent;
        }
        tiyData.tParams.userNoteList.length=0;
        if(record.noteList!=null){
          record.noteList.forEach(function(item){
            tiyData.tParams.userNoteList.push(item);
          })

        }



      tiyData.tStatus.modalUserInfo.isShow=true;
    } else {
      self.$Message.error(response.errorMessage);
    }
  });

}

/**
 * 从服务器请求订单详情
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webOrderDetail = (self, tiyData, id) => {
  self.openCollapse = "0";
  self.$Spin.show();
  // tiyData.tStatus.modalDeliver.params.selectedOrderItem = [];
  self.$apiOrder.orderDetail({
    "id": id,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      var result = response.result;
      tiyData.tData.orderDetail.actualPayment = result.actualPayment;
      tiyData.tData.orderDetail.addressId = result.addressId;
      tiyData.tData.orderDetail.checkoutTime = result.checkoutTime;
      tiyData.tData.orderDetail.clientId = result.clientId;
      tiyData.tData.orderDetail.country = result.country;
      tiyData.tData.orderDetail.countryName = result.countryName;
      tiyData.tData.orderDetail.createtime = result.createtime;
      tiyData.tData.orderDetail.deliveryMethod = result.deliveryMethod;
      tiyData.tData.orderDetail.deliveryMethodName = result.deliveryMethod == 100 ? "普通快递" : "商业快递";
      tiyData.tData.orderDetail.deviceType = result.deviceType;
      if(result.payWay!=''&&result.payWay!=null){
        tiyData.tData.orderDetail.payWayName = self.$store.getters.dictionaries.payTypeDict.filter(itemDict => itemDict.value == result.payWay)[0].name;
      }


      // result.discounts.forEach(function (item) {
      //   tiyData.tData.orderDetail.discounts.push(item);
      // });
      tiyData.tData.orderDetail.id = result.id;
      tiyData.tData.orderDetail.itemCount = result.itemCount;
      // result.items.forEach(function (item) {
      //   tiyData.tData.orderDetail.items.push(item);
      // });
      tiyData.tData.orderDetail.note = result.note;
      tiyData.tData.orderDetail.orderPostage = result.orderPostage;
      tiyData.tData.orderDetail.originalPrice = result.originalPrice;
      tiyData.tData.orderDetail.packages.length = 0;
      result.packages.forEach(function (packageItem) {
        if (packageItem.state) {
          packageItem.stateTitle = self.$store.getters.dictionaries.packageStateDict.filter(itemDict => itemDict.value == packageItem.state)[0].name;
        } else {
          packageItem.stateTitle = '';
        }
        tiyData.tData.orderDetail.packages.push(packageItem);
        packageItem.products.forEach(function(product){ //只有已经发货状态的订单项可以修改运单号
          product.items.forEach(function(item){
            if(item.state != 112 && item.state != 113){
              item._disabled = true;
            }
          });
        });
      });
      tiyData.tData.orderDetail.payWay = result.payWay;
      if (0 != tiyData.tData.orderDetail.payWay) {
        tiyData.tData.orderDetail.payWayName = self.$store.getters.dictionaries.payTypeDict.filter(item => item.value == result.payWay)[0].name;
      } else {
        tiyData.tData.orderDetail.payWayName = '未支付';
      }
      tiyData.tData.orderDetail.payer = result.payer;
      tiyData.tData.orderDetail.paymentAccount = result.paymentAccount;
      tiyData.tData.orderDetail.paymentSerialNumber = result.paymentSerialNumber;
      tiyData.tData.orderDetail.postage = result.postage;
      tiyData.tData.orderDetail.productCount = result.productCount;
      var addressJson = self.$toJson(result.receiverInfo);
      tiyData.tData.orderDetail.receiverInfo.userFullName = addressJson.userFullName;
      tiyData.tData.orderDetail.receiverInfo.userPhoneNumber = addressJson.userPhoneNumber;
      tiyData.tData.orderDetail.receiverInfo.countryName = addressJson.countryName;
      tiyData.tData.orderDetail.receiverInfo.countryCode = addressJson.countryCode;
      tiyData.tData.orderDetail.receiverInfo.postalCode = addressJson.postalCode;
      tiyData.tData.orderDetail.receiverInfo.unit = addressJson.unit;
      tiyData.tData.orderDetail.receiverInfo.streetAddress = addressJson.streetAddress;
      tiyData.tData.orderDetail.receiverInfo.cityName = addressJson.cityName;
      tiyData.tData.orderDetail.receiverInfo.state = addressJson.state;
      tiyData.tData.orderDetail.serialNumber = result.serialNumber;
      tiyData.tData.orderDetail.state = result.state;
      tiyData.tData.orderDetail.stateTitle = self.$store.getters.dictionaries.orderStateDict.filter(item => item.value == result.state)[0].name;
      tiyData.tData.orderDetail.stateName = result.stateName;
      tiyData.tData.orderDetail.userId = result.userId;
      tiyData.tData.orderDetail.userName = result.userName;
      tiyData.tData.orderDetail.weight = result.weight;
      tiyData.tStatus.modalOrderDetail.isShow = true;
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};
export const webItemRecord = (self, tiyData,orderItemId) => {
  self.$Spin.show();
  self.$apiOrder.getItemRecord({
    "orderItemId": orderItemId,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      response.result.forEach(function (item) {
        tiyData.tData.selectRecord.push(item);
      });
      tiyData.tStatus.modalUserRecord.isShow = true
    }
  });
};

export  const saveNote = (self, tiyData) =>{
  self.noteModal.isLoading=false;
  self.$refs['noteForm'].validate((valid) => {
    if(valid){
      self.$Spin.show();
    let sequence = tiyData.tParams.userNoteList.length+1;
    let note = tiyData.tData.note;
    let userId = tiyData.tData.note.userId;
    let name = tiyData.tData.note.name;
    let content = tiyData.tData.note.content;
    var usernote={
      name:name,
      content:content,
      userId:userId,
      sequence:sequence
    };
    self.$apiUser.saveNote({
      userNote:usernote
    }).then(function (response) {
      if (response.success) {
        usernote.id = response.result;
        tiyData.tParams.userNoteList.push(usernote);
        self.noteModal.isLoading=false;
        self.$Spin.hide();
      } else {
        self.noteModal.isLoading=false;
        self.$Spin.hide();
        self.$Message.error(response.errorMessage);
      }
      self.noteModal.isShow=false;
    });
    }else{
      changeNoteModelLoading(self,tiyData);
    }


  })

}
export  const deleteUserNote = (self, tiyData,index) =>{
  self.$Spin.show();
  let noteId =  tiyData.tParams.userNoteList[index].id;
  self.$apiUser.deleteNote({
    noteId:noteId
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.tParams.userNoteList.splice(index,1);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
}

function changeNoteModelLoading(self, tiyData) {
  self.noteModal.isLoading = false;
  self.$nextTick(function () {
    self.noteModal.isLoading = true;
  });
}
export  const actionActive = (self, tiyData) => {
  self.$Spin.show();
  self.$apiUser.activeUser({
    activeInfo:tiyData.tData.activeInfo
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Message.success("激活用户成功！");
      self.status.activeModal.isShow = false;
      webList(self, tiyData);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });

}

